package com.huluobo.a2307monthdemo2.live

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2307monthdemo2.R
import com.huluobo.a2307monthdemo2.adapter.GiftAdapter
import com.huluobo.a2307monthdemo2.adapter.GoodsAdapter
import com.huluobo.a2307monthdemo2.adapter.MessageAdapter
import com.huluobo.a2307monthdemo2.databinding.ActivityLiveBinding
import com.huluobo.a2307monthdemo2.shop.DetailActivity
import com.huluobo.a2307monthdemo2.utils.ImageUtils
import com.huluobo.lib_base.bean.GiftBean
import com.huluobo.lib_base.bean.MessageEntity
import com.huluobo.lib_base.bean.Money
import com.huluobo.lib_base.bean.VideoBean
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.mvvm.MessageEvent
import com.huluobo.lib_base.net.Const
import com.hyphenate.EMCallBack
import com.hyphenate.EMChatRoomChangeListener
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import top.littlefogcat.danmakulib.danmaku.Danmaku
import top.littlefogcat.danmakulib.danmaku.DanmakuManager

@AndroidEntryPoint
class LiveActivity : BaseActivity<ActivityLiveBinding, LiveViewModel>() {
    private lateinit var videoBean: VideoBean
    private lateinit var giftAdapter: GiftAdapter
    private lateinit var giftBean: GiftBean
    private lateinit var money: Money
    private lateinit var messageAdapter: MessageAdapter
    private lateinit var goodsAdapter: GoodsAdapter
    override fun initData() {
        vm.queryMoneySuccess.observe(this) {
            money = it
            binding.liveUserMoneyTv.text = "余额:${money.money}抖币"
        }

        vm.followSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "已关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
            videoBean.guanzhu = 1
            EventBus.getDefault().post(MessageEvent("1"))
        }

        vm.unFollowSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
            videoBean.guanzhu = 0
            EventBus.getDefault().post(MessageEvent("0"))
        }

        vm.getGiftSuccess.observe(this) {
            giftAdapter.data.clear()
            giftAdapter.data.addAll(it)
            giftAdapter.notifyDataSetChanged()
        }

        vm.updateMoneySuccess.observe(this) {
            Log.e("TagA", it)
        }

        vm.getGoodsSuccess.observe(this) {
            goodsAdapter.data.clear()
            goodsAdapter.data.addAll(it)
            goodsAdapter.notifyDataSetChanged()
        }
    }

    override fun onResume() {
        super.onResume()
        vm.queryMoney(SPUtils.getInstance().getString(Const.PARAM_USERNAME))
    }

    override fun initView() {
        videoBean = intent.getSerializableExtra(Const.KEY_VIDEO_BEAN) as VideoBean

        binding.livePlayer.backButton.visibility = View.GONE
        binding.livePlayer.setUp(videoBean.videopath, true, "")

        ImageUtils.loadICircleImage(this, videoBean.headpath, binding.liveUserIconIv)
        binding.liveUsernameTv.text = videoBean.authname

        binding.liveFollowBtn.text = if (videoBean.guanzhu == 0) "关注" else "已关注"
        binding.liveFollowBtn.setBackgroundResource(if (videoBean.guanzhu == 0) R.drawable.shape_red else R.drawable.shape_alpha_black)
        binding.liveLikeCountTv.text = "${videoBean.like_count}人喜欢"

        binding.liveFollowBtn.setOnClickListener {
            val map = mapOf(
                Const.PARAM_AUTHNAME to videoBean.authname
            )
            if (videoBean.guanzhu == 0) {
                vm.followAuth(map)
            } else {
                vm.unFollowAuth(map)
            }
        }

        binding.liveLikeView.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5,
        )

        binding.liveLikeIv.setOnClickListener {
            binding.liveLikeView.addFavor()
        }

        binding.liveDanmuIv.setOnClickListener {
            binding.liveDanmuLl.visibility = View.VISIBLE
        }

        binding.liveDanmuSendIv.setOnClickListener {
            val danmuString = binding.liveDanmuEt.text.toString()
            if (danmuString.isNotEmpty()) {
                val danmuku = Danmaku()
                danmuku.text = danmuString
                danmuku.size = 30
                DanmakuManager.getInstance().init(this, binding.liveDanmuView)
                DanmakuManager.getInstance().send(danmuku)

                binding.liveDanmuEt.text.clear()
                binding.liveDanmuLl.visibility = View.GONE
            } else {
                ToastUtils.showLong("弹幕内容不能为空")
            }
        }

        binding.liveGiftRv.layoutManager = GridLayoutManager(this, 5)
        giftAdapter = GiftAdapter()
        binding.liveGiftRv.adapter = giftAdapter

        giftAdapter.setOnItemClickListener { adapter, view, position ->
            giftBean = giftAdapter.data[position]
            ImageUtils.loadImage(this, giftBean.giftpath, binding.liveGiftSelectIv)
            binding.liveGiftSelectTv.text = giftBean.giftname
        }

        binding.liveGiftIv.setOnClickListener {
            binding.liveGiftCl.visibility = View.VISIBLE
            vm.getGift()
        }

        binding.liveCloseTv.setOnClickListener {
            binding.liveGiftCl.visibility = View.GONE
        }

        binding.liveGiftSendBtn.setOnClickListener {
            sendGift()
        }

        binding.livePayBtn.setOnClickListener {
            startAct(PayActivity::class.java)
        }

        binding.liveInputTv.setOnClickListener {
            binding.liveChatLl.visibility = View.VISIBLE
        }

        messageAdapter = MessageAdapter()
        binding.liveChatRv.layoutManager = LinearLayoutManager(this)
        binding.liveChatRv.adapter = messageAdapter

        initChatRoom()

        binding.liveChatSendIv.setOnClickListener {
//            val msg =
//                MessageEntity(SPUtils.getInstance().getString(Const.PARAM_USERNAME), binding.liveChatEt.text.toString())
//            messageAdapter.data.add(msg)
//            messageAdapter.notifyDataSetChanged()
//
//            binding.liveChatRv.scrollToPosition(messageAdapter.data.size - 1)
//            binding.liveChatEt.text.clear()
//            binding.liveChatLl.visibility = View.GONE
            sendMessage()
        }

        binding.liveCartIv.setOnClickListener {
            showCart()
        }

        binding.liveCloseIv.setOnClickListener {
            closeCart()
        }
    }

    private fun closeCart() {
        val animOut = AnimationUtils.loadAnimation(this, R.anim.anim_out)
        animOut.duration = 500
        animOut.interpolator = AccelerateInterpolator()
        animOut.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                binding.liveCartCl.visibility = View.GONE
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        binding.liveCartCl.startAnimation(animOut)
    }

    private fun showCart() {
        vm.getGoods(1, 20)
        binding.liveCartCl.visibility = View.VISIBLE
        val animIn = AnimationUtils.loadAnimation(this, R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        binding.liveCartCl.startAnimation(animIn)

        binding.liveCartRv.layoutManager = GridLayoutManager(this, 2)
        goodsAdapter = GoodsAdapter()
        binding.liveCartRv.adapter = goodsAdapter

        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            val goodsId = goodsAdapter.data[position].id
            val intent = Intent(this, DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, goodsId)
            startActivity(intent)
        }

    }

    private fun sendMessage() {
        if (binding.liveChatEt.text.toString().isNotEmpty()) {
            val emMessage = EMMessage.createTextSendMessage(binding.liveChatEt.text.toString(), Const.CHAT_ROOM_ID)
            emMessage.chatType = EMMessage.ChatType.ChatRoom
            EMClient.getInstance().chatManager().sendMessage(emMessage)
            emMessage.setMessageStatusCallback(object : EMCallBack {
                override fun onSuccess() {
                    val messageEntity = MessageEntity(
                        EMClient.getInstance().currentUser,
                        binding.liveChatEt.text.toString()
                    )
                    messageAdapter.data.add(messageEntity)
                    runOnUiThread {
                        messageAdapter.notifyDataSetChanged()
                        binding.liveChatRv.scrollToPosition(messageAdapter.data.size - 1)
                        binding.liveChatEt.text.clear()
                        binding.liveChatLl.visibility = View.GONE
                    }
                }

                override fun onError(code: Int, error: String?) {
                    Log.e("TagA", "发送消息失败;$code error:$error")
                }
            })

        } else {
            ToastUtils.showLong("发送消息不能为空")
        }
    }

    private fun initChatRoom() {
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(charRoomListener)

        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, object : EMValueCallBack<EMChatRoom> {
            override fun onSuccess(value: EMChatRoom?) {
                Log.e("TagA", "加入聊天室成功")
            }

            override fun onError(error: Int, errorMsg: String?) {
                Log.e("TagA", "加入聊天室失败:$error,$errorMsg")
            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID)
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().removeChatRoomListener(charRoomListener)
    }

    //接受消息监听器
    private val messageListener = EMMessageListener {
        it.forEach { emMessage ->
            val user = emMessage.userName
            val msg = (emMessage.body as EMTextMessageBody).message
            val messageEntity = MessageEntity(user, msg)
            messageAdapter.data.add(messageEntity)
            runOnUiThread {
                messageAdapter.notifyDataSetChanged()
                binding.liveChatRv.scrollToPosition(messageAdapter.data.size - 1)
            }
        }
    }

    //用于监听用户进入和退出
    private val charRoomListener = object : EMChatRoomChangeListener {
        override fun onChatRoomDestroyed(roomId: String?, roomName: String?) {
        }

        override fun onMemberJoined(roomId: String?, participant: String?) {
            runOnUiThread {
                messageAdapter.data.add(MessageEntity("系统", "${participant}进入直播间"))
                messageAdapter.notifyDataSetChanged()
            }

        }

        override fun onMemberExited(roomId: String?, roomName: String?, participant: String?) {
            runOnUiThread {
                messageAdapter.data.add(MessageEntity("系统", "${participant}退出直播间"))
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onRemovedFromChatRoom(reason: Int, roomId: String?, roomName: String?, participant: String?) {
        }

        override fun onMuteListAdded(chatRoomId: String?, mutes: MutableList<String>?, expireTime: Long) {
        }

        override fun onMuteListRemoved(chatRoomId: String?, mutes: MutableList<String>?) {
        }

        override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {
        }

        override fun onAdminAdded(chatRoomId: String?, admin: String?) {
        }

        override fun onAdminRemoved(chatRoomId: String?, admin: String?) {
        }

        override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {
        }

        override fun onAnnouncementChanged(chatRoomId: String?, announcement: String?) {
        }
    }

    private fun sendGift() {
        if (money.money < giftBean.price) {
            ToastUtils.showLong("用户余额不足,请充值")
            return
        }

        val newMoney = money.money - giftBean.price
        binding.liveUserMoneyTv.text = "余额:${newMoney}抖币"
        money.money = newMoney
        vm.updateMoney(money)

        val giftAnimView = ImageView(this)
        val params = ConstraintLayout.LayoutParams(200, 200)
        giftAnimView.layoutParams = params

        binding.liveRootCl.addView(giftAnimView)
        ImageUtils.loadImage(this, giftBean.giftpath, giftAnimView)

        val screenHeight = binding.liveRootCl.measuredHeight
        val screenWidth = binding.liveRootCl.measuredWidth

        val translationY = ObjectAnimator.ofFloat(
            giftAnimView,
            "translationY",
            screenHeight.toFloat(),
            (screenHeight / 5 * 3).toFloat(),
            (screenHeight / 3).toFloat(),
            (screenHeight / 2).toFloat(),
            (screenHeight / 3 * 2).toFloat(),
            (screenHeight / 2).toFloat(),
        )

        val translationX = ObjectAnimator.ofFloat(
            giftAnimView,
            "translationX",
            (screenWidth / 2).toFloat(),
            0f,
            (screenWidth / 2).toFloat(),
            screenWidth.toFloat(),
            (screenWidth / 2).toFloat(),
            (screenWidth / 3).toFloat(),
        )

        val rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 1f, 1f, 1f, 1f, 1f, 0f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.playTogether(translationX, translationY, rotation, scaleY, scaleX, alpha)
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                binding.liveGiftCl.visibility = View.GONE
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                binding.liveRootCl.removeView(giftAnimView)
            }
        })
        animatorSet.start()
    }
}